<?php

class SQL extends Singleton
{
  private $connection;
  private $queryResult;
  
  protected function __construct() {
    // $this->logger = Logger::getInstance();
  }
  
  public static function & factory() {
      return parent::getSingleton(__CLASS__);
  }
  
  public function connect($host = "localhost", $user = "root", $passwd = "")
  {
    $this->connection = @mysql_connect($host, $user, $passwd);
    
    if(mysql_errno()) 
      throw new MTException("Could not connect to dabatase", EXCEPTION_FATAL_DB, mysql_error());
    
  }
  
  public function query($query)
  {
    $this->queryResult = @mysql_query($query);
    //echo $query;
    if(!$this->queryResult)
      throw new MTException("An error occured while quering the database ( $query )", EXCEPTION_ERROR_DB_QUERY, mysql_error());
    
    $this->queryResult;
    return $this;
  }
  
  public function fetchObject($r=null)
  {
    if($r != null) $this->queryResult = $r;
    $fetchResult = @mysql_fetch_object($this->queryResult);
    
    if(mysql_errno()) 
      throw new MTException("An error occured while fetching from database", EXCEPTION_ERROR_DB_FETCH, mysql_error());
    
    return $fetchResult;
  }
  
  public function fetchArray($r=null, $result_type = MYSQL_ASSOC)
  {
    if($r != null) $this->queryResult = $r;
    $fetchResult = @mysql_fetch_array($this->queryResult, $result_type);
    
    if(mysql_errno()) 
      throw new MTException("An error occured while fetching from database", EXCEPTION_ERROR_DB_FETCH, mysql_error());
    
    return $fetchResult;
  }
  
  public function numRows($r=null)
  {
    if($r != null) $this->queryResult = $r;
    $numRows = @mysql_num_rows($this->queryResult); // or trigger_error(mysql_error());
    
    if(mysql_errno()) 
      throw new MTException("", EXCEPTION_WARNING_DB_NUMROWS, mysql_error());
    
    return $numRows;
  }
  
  public function numAffectedRows()
  {
    $numRows = @mysql_affected_rows(); // or trigger_error(mysql_error());
    
    if(mysql_errno()) 
      throw new MTException("", EXCEPTION_WARNING_DB_NUMROWS, mysql_error());
    
    return $numRows;
  }
}

?>
